package com.wb.lambda.first;

import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 并行流
 */
public class ParallelStreams {

    private static final Logger logger = LoggerFactory.getLogger(ParallelStreams.class);

    public List<Integer> resourceList;

    @Before
    public void beforM() {
        int index = 0, size = 999;
        resourceList = Lists.newArrayList(size);
        while (index < size) {
            resourceList.add(index);
            index++;
        }
        logger.info("完成初始化!");
    }

    public static long iterativeSum(long n) {
        try {
            Thread.sleep(1000L * 2);
        } catch (InterruptedException e) {
            logger.error("", e);
        }
        return n * 2;
    }

    @Test
    public void testBingXing() {
        // 串行化
        long beginTime = System.nanoTime();
        resourceList.stream()
                .filter(i -> i % 2 == 0)
                .collect(Collectors.toList());
        long endTime = System.nanoTime();
        logger.info("串行化 : {} " , (endTime - beginTime) / 1_000_000);

        // 并行化
        beginTime = System.nanoTime();
        resourceList.stream()
                .parallel()
                .filter(i -> i % 2 == 0)
                .collect(Collectors.toList());
        endTime = System.nanoTime();
        logger.info("并行化 : {} " , (endTime - beginTime) / 1_000_000);
    }
}
